package com.foss;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import com.foreveross.chameleonsdk.config.URL;

import java.util.List;
/**
 * project:
 * author: wzq
 * date: 2014/7/21
 * description: 通用 常用 工具方法
 */
public class GeneralUtils {

    // 网络是否连接
    public static boolean isNetworkConnected() {
        Context context = ChameleonApplication.getApplication();
        ConnectivityManager manager = (ConnectivityManager) context.getApplicationContext()
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        if(manager == null) {
            return false;
        }

        NetworkInfo networkinfo = manager.getActiveNetworkInfo();
        return (networkinfo != null) && networkinfo.isAvailable();
    }

    // 当前程序是否在运行状态
    public static boolean isAppRunning() {
        Context ctx = ChameleonApplication.getApplication();
        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> list = am.getRunningTasks(100);
        boolean isAppRunning = false;
        String MY_PKG_NAME = URL.APP_PACKAGENAME;
        for(RunningTaskInfo info : list) {
            if(info.topActivity.getPackageName().equals(MY_PKG_NAME) || info.baseActivity.getPackageName()
                    .equals(MY_PKG_NAME)) {
                isAppRunning = true;
                break;
            }
        }
        return isAppRunning;
    }

    /**
     * 拷贝byte数组
     * @param src
     */
    public static byte[] copyBytes(byte[] src) {
        byte[] copy = new byte[src.length];
        for(int i = 0; i < src.length; i++) {
            copy[i] = src[i];
        }
        return copy;
    }

    public static int getVersionCode() {
        Application app = ChameleonApplication.getApplication();
        PackageInfo pi;
        try {
            pi = app.getPackageManager().getPackageInfo(app.getPackageName(), 0);
            return pi.versionCode;
        } catch(NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
